package com.oauth.twitter.server.controller;

import java.util.List;

import org.gwtwidgets.server.spring.GWTSpringController;
import org.gwtwidgets.server.spring.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.oauth.common.server.util.OAuthRequestUtil;
import com.oauth.logging.OAuthLogger;
import com.oauth.twitter.client.beans.Tweet;
import com.oauth.twitter.client.beans.TwitterModel;
import com.oauth.twitter.client.exception.TwitterOAuthException;
import com.oauth.twitter.client.rpc.TwitterRemoteService;
import com.oauth.twitter.server.service.TwitterService;

public class TwitterGwtController extends GWTSpringController implements TwitterRemoteService {

	private static final long serialVersionUID = -5758464341967618224L;

	@Autowired
	private TwitterService twitterService;

	private OAuthLogger logger = OAuthLogger.getLogger(this.getClass());

	@Override
	public Tweet updateTweet(String pTweetText) throws TwitterOAuthException {
		Tweet updatedTweet = null;
		try {
			updatedTweet = twitterService.updateTweet(pTweetText,
					OAuthRequestUtil.getMemberId(ServletUtils.getRequest()));
		} catch (Exception e) {
			logger.error("Error in updating tweet", e);
			throw new TwitterOAuthException();
		}
		return updatedTweet;
	}

	@Override
	public TwitterModel getTweets() throws TwitterOAuthException {
		TwitterModel model = new TwitterModel();
		Long memberId = OAuthRequestUtil.getMemberId(ServletUtils.getRequest());
		try {
			List<Tweet> tweets = twitterService.getTweets(memberId);
			model.setTweets(tweets);
			model.setUser(twitterService.getUserInfo(memberId));
			return model;
		} catch (Exception e) {
			logger.error("Error in updating tweet", e);
			throw new TwitterOAuthException();
		}

	}

	/**
	 * @param twitterService
	 *            the twitterService to set
	 */
	public void setTwitterService(TwitterService twitterService) {
		this.twitterService = twitterService;
	}

}
